# -*- coding: utf-8 -*-
"""
Created on Sun Jul  2 15:16:33 2017

@author: claude
"""

import  json
import pymongo
from item import Item
import Token
from  util import ErrorInfo
from time import sleep

class MongoClint():
    collection_item = 'items'
    def __init__(self):
        self.client = pymongo.MongoClient('localhost', 27017)
        self.db = self.client.weidian
        
    def check_item_in_db(self, keyword):
        return self.db[self.collection_item].find_one({"keyword":keyword})!=None
        
    def get_item_in_db(self, keyword):
        return self.db[self.collection_item].find_one({"keyword":keyword})
        
    def save_item_to_db(self, item):
        try:
            self.db[self.collection_item].insert(item)
        except pymongo.errors.DuplicateKeyError:
            print '_id %s has been existed', item["_id"]
    
if __name__=="__main__":
    access_token = Token.TokenGen()
    try:
        result = Item.list_shop_items(access_token,page_num=1,page_size=1,orderby=1,version="1.0",path="api")
    except ErrorInfo.OpenError: 
        sleep(10)
        access_token = Token.TokenGen()
    mongodb = MongoClint()
    total_pages = int(result['result']['total_num']/20)+1
    for page_num in range(1,total_pages):
        result = Item.list_shop_items(access_token,page_num=page_num,page_size=20,orderby=1,version="1.0",path="api")
        for x in result['result']['items']:
            x['_id'] = x['itemid']
            mongodb.save_item_to_db(x)
            #item_id = x['itemid']
            #res = Item.get_item(item_id,access_token,version="1.0",path="api")
            #print json.dumps(res)